﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.XPath;
using Microsoft.Office.InfoPath;

namespace InfoPathDebugger
{
    public partial class ChangeValueForm : Form
    {
        public ChangeValueForm(DataSourceCollection dataSources)
        {
            InitializeComponent();
            initializeDataSourceDropdownList(dataSources);
        }

        private void initializeDataSourceDropdownList(DataSourceCollection dataSources)
        {
            foreach (DataSource ds in dataSources)
            {
                DataSourceListItem dsListItem = new DataSourceListItem(ds);
                cbDataSource.Items.Add(dsListItem);
            }

            if (cbDataSource.Items.Count > 0)
            {
                cbDataSource.SelectedIndex = 0;
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            // Retrieve the selected data source.
            DataSource selectedDS = ((DataSourceListItem)cbDataSource.SelectedItem).InfoPathDataSource;

            // Retrieve xpath, value and namespace prefix from text box.
            String xpath = tbXPath.Text;
            String value = tbValue.Text;
            String nsPrefix = tbNSPrefix.Text;

            if (!XPathHelper.SetNodeValue(selectedDS.CreateNavigator(), xpath, value, nsPrefix))
            {
                MessageBox.Show(String.Format("Failed to set value '{0}' to node '{1}'", value, xpath), "Failed to set value", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            this.Close();
        }
    }

    internal class DataSourceListItem
    {
        public DataSourceListItem(DataSource dataSource)
        {
            _dataSource = dataSource;
        }

        public DataSource InfoPathDataSource
        {
            get
            {
                return _dataSource;
            }
        }

        public override string ToString()
        {
            String dataSourceName = _dataSource.Name;
            return String.IsNullOrEmpty(dataSourceName) ? "Main" : dataSourceName;
        }

        private DataSource _dataSource;
    }
}
